package com.yueyang.sojourn.server.validation;

import com.yueyang.sojourn.server.model.dto.AddTouristDto;
import com.yueyang.sojourn.server.model.dto.EditTouristDto;
import com.yueyang.sojourn.server.model.enums.CardTypeEnum;
import com.yueyang.sojourn.server.utils.CardValidUtil;
import com.yueyang.sojourn.server.validation.annotation.CardNoValid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 证件验证
 * @author Andy.yang
 * @version v1
 * @summary
 * @Copyright (c) 2019, YueYang Group All Rights Reserved.
 * @since 2020/3/19
 */
public class CardNoValidator implements ConstraintValidator<CardNoValid, Object> {
    @Override
    public boolean isValid(Object touristDto, ConstraintValidatorContext constraintValidatorContext) {

        Integer cardType = null;
        String cardNo = null;
        if(touristDto.getClass() == AddTouristDto.class){
            cardType = ((AddTouristDto)touristDto).getCardType();
            cardNo = ((AddTouristDto)touristDto).getCardNo();
        }else if(touristDto.getClass() == EditTouristDto.class){
            cardType = ((EditTouristDto)touristDto).getCardType();
            cardNo = ((EditTouristDto)touristDto).getCardNo();
        }

        boolean rs = false;
        String  msg = "证件";
        if(cardType.equals(CardTypeEnum.ID.getCode())){
            rs = CardValidUtil.validIdCard(cardNo);
            msg = "身份证";
        }else if(cardType.equals(CardTypeEnum.PASSPORT.getCode())){
            rs = CardValidUtil.validPassport(cardNo);
            msg = "护照";
        }else if(cardType.equals(CardTypeEnum.HKPASS.getCode())){
            rs = CardValidUtil.validHKPass(cardNo);
            msg = "港澳通行证";
        }else if(cardType.equals(CardTypeEnum.TW.getCode())){
            rs = CardValidUtil.validTaiwanCN(cardNo);
            msg = "台胞证";
        }else if(cardType.equals(CardTypeEnum.TWPASS.getCode())){
            rs = CardValidUtil.validTWPass(cardNo);
            msg = "台湾通行证";
        }else if(cardType.equals(CardTypeEnum.HOMETOWN.getCode())){
            rs = CardValidUtil.validReturnHome(cardNo);
            msg = "回乡证";
        }
        msg = "[" + msg + "]格式不正确";

        //重新添加错误提示语句
        constraintValidatorContext.disableDefaultConstraintViolation();
        constraintValidatorContext
                .buildConstraintViolationWithTemplate(msg).addConstraintViolation();
        return rs;
    }
}
